""" java libraries """
from java.awt import Color
from java.awt import Font
from java.util import Locale
from java.io import File
from java.text import DecimalFormat
""" jhplot libraries """
from jhplot.jadraw import JaText
from jhplot  import HPlotJa
from jhplot  import H1D
from jhplot  import F1D
""" Philippe's libraries """
from fr.in2p3.ipnl.aidautilities import AidaUtil
""" jscinttools libraries """
from jscinttools.datafit import DataFitter
from jscinttools.datafit import FitSettings
from jscinttools.datafit import FitFuncFactory
from jscinttools.utilities.aidautilities import AidaFileReader
from jscinttools.utilities.aidautilities import AUtil
from jscinttools.utilities.jhplotutilities import HPlotJaUtil

Locale.setDefault(Locale.ENGLISH) #For French OS
ff = FitFuncFactory.specFuncFactory()

showFigures = False
writeFigures = not showFigures

"""
###############################################################
# Define the Path and files names
###############################################################
"""
#aidaPath = "/home/marc-antoine/Documents/ZnWO4/Run_5/Reduced/TDC/2011_07_04/"
#aidaFile = "Am241Cs137_295K_511_PhotonReanalysis_NoTuples"
#outPath = aidaPath
#startPar = [1, 253, 17, 0.6, 175, 17, 1.6, 60, 17, 2, 20, 5, 1, 46, 27]
#fitFunc = ff.nGaussMoyal()
#win = [0, 350, 0, 2]
#title = "ZnWO_{4} - Spectrum at 295 K"
#source = "Sources: ^{241}Am + ^{137}Cs"
#preliminary = True

aidaPath = "/home/marc-antoine/Documents/ZnWO4/Run_5/Reduced/TDC/2011_07_04/"
aidaFile = "Am241_295K_511_PhotonReanalysis_NoTuples"
outPath = aidaPath
startPar = [1, 253, 17, 2, 20, 5, 1, 46, 27, 0.1, 500]
fitFunc = ff.nGaussMoyalExp()
win = [0, 350, 0, 2]
title = "ZnWO_{4} - Spectrum at 295 K"
source = "Source: ^{241}Am"
preliminary = True

"""
###############################################################
"""

outputFile = "Spectrum" + aidaFile.split("_PhotonReanalysis_NoTuples")[0]
specPath = "Reanalysis/Ch2 Plus Ch1 Total Photons,Some Cuts"

afr = AidaFileReader(aidaPath, aidaFile)
specHisto = afr.grabHisto1D(specPath)
normFac = AUtil.maxBinHeight(specHisto, [150, 400])
specHisto.scale(1.0 / normFac)

df = DataFitter(fitFunc)
fs = FitSettings(startPar)
fitRes = df.doFit(specHisto, fs)
print(AidaUtil.printResultsOfFit(fitRes))

fmt = DecimalFormat("#.##");
fmtSc = DecimalFormat("0.##E0");

fitResVal = fitRes.fittedParameters()
fitResValErr = fitRes.errors()
fitResValF = []
fitResValErrF = []
fitResStr = []
for i in range(len(fitResVal)):
	fitResValF.append(fmt.format(fitResVal[i]))
	fitResValErrF.append(fmt.format(fitResValErr[i]))
	fitResStr.append(fitResValF[i] + " &plusmn; " + fitResValErrF[i])
chi2Val = fitRes.quality()
chi2ValF = fmt.format(chi2Val)

statLine = []
statLine.append("Amp = " + fitResStr[0])
statLine.append("&micro; = " + fitResStr[1])
statLine.append("&sigma; = " + fitResStr[2])
statLine2 = []
statLine2.append("Amp = " + fitResStr[3])
statLine2.append("&micro; = " + fitResStr[4])
statLine2.append("&sigma; = " + fitResStr[5])


"""
###############################################################
# Plotting Part
###############################################################
"""
""" Define colors and fonts"""
figType = [".png", ".eps", ".pdf"]
colors = [Color.blue, Color.red, Color(0, 170, 0), Color.black, Color.yellow]
axisLabelFont = Font(Font.SERIF, Font.PLAIN, 25)
titleFont = Font(Font.SERIF, Font.PLAIN, 25)
legendFont = Font(Font.SERIF, Font.PLAIN, 25)
ticFont = Font(Font.SERIF, Font.PLAIN, 20)
statBoxFont = Font(Font.SERIF, Font.PLAIN, 15)
prelimFont = Font(Font.SERIF, Font.BOLD, 30)


""" Create the plottable jhplot objects from AIDA IObjects"""
spec = H1D(specHisto)
spec.setTitle(aidaFile)
spec.setStyle("h")
spec.setColor(colors[0])
spec.setPenWidth(2)
spec.setErrAll(False)

fit = F1D(fitRes.fittedFunction(), win[0], win[1])
fit.setTitle("Fit")
fit.setColor(colors[1])
fit.setPenWidth(2)
fit.setPoints(1000)


statBox = [] #Some Fit Results
for i in range (len(statLine)):
	statBox.append(JaText(statLine[i], 0.6, 0.375+(i*0.035), "NDC"))
	statBox[i].setFont(statBoxFont)
	statBox[i].setColor(colors[3])
	

statBox2 = [] #Some Other Fit Results
for i in range (len(statLine2)):
	statBox2.append(JaText(statLine2[i], 0.35, 0.5+(i*0.035), "NDC"))
	statBox2[i].setFont(statBoxFont)
	statBox2[i].setColor(colors[3])


prelim = JaText("PRELIMINARY", 0.05, 0.35, "NDC")
prelim.setFont(prelimFont)
prelim.setColor(colors[1])
prelim.setRotAngle(-45)

src = JaText(source, 0.3, 0.25, "NDC")
src.setFont(legendFont)
src.setColor(colors[0])

""" Create the Plotter"""
plotter = HPlotJa("Average Event", 600, 600, 1, 1, True)
plotter.setGTitle(title + " - &Chi;^{2}=" + chi2ValF, titleFont)
plotter.antiAlias = False
plotter.setPad(1, 1, 0.125, 0.125, 0.75, 0.75)
plotter.setRange(win[0], win[1], win[2], win[3])
plotter.setLogScale(0, False)
plotter.setLogScale(1, False)
plotter.setTicFont(ticFont)
plotter.setShowStatBox(False)
plotter.showKey(False)
plotter.setNameX("Total Number of Photons")
plotter.setNameY("Counts (a.u.)")
if showFigures:
	plotter.visible(True)
else:
	plotter.visible(False)

""" Plots all the jhplot objects"""
if preliminary:
	plotter.draw(prelim)
plotter.draw(spec)
plotter.draw(fit)
for i in range (len(statLine)):
	plotter.draw(statBox[i])
#for i in range (len(statLine2)):
#	plotter.draw(statBox2[i])
plotter.draw(src)

plotter.cd(1,1)
theAxes_11 = plotter.getPad()
theAxes_11.setLabelSpace(0, 0.0)
theAxes_11.setLabelSpace(1, 0.0)
HPlotJaUtil.setTickLabelZeroPositive(theAxes_11)


""" Modifies the JaAxes and the axes labels"""
labX = plotter.getLabelX()[0][0]
labX.setFont(axisLabelFont)
HPlotJaUtil.setLabelLocationAtCenter(0, labX, plotter, 0.025)
labY = plotter.getLabelY()[0][0]
labY.setFont(axisLabelFont)
HPlotJaUtil.setLabelLocationAtCenter(1, labY, plotter, -0.01)
 

plotter.update()

""" Saves or not the plot"""
if writeFigures:
	for i in range(len(figType)):
		outFileName = outputFile + figType[i]
		plotter.export(outPath + File.separator + outFileName)
		print("Writting File : " + outPath + File.separator + outFileName)
		
print("That's all folks !")
if (not showFigures):
	exit()
